//
//  UIImageView+JW.m
//  HaiXing
//
//  Created by lifayu on 16/3/18.
//  Copyright © 2016年 xinli. All rights reserved.
//

#import "UIImageView+JW.h"
#import <UIImage+GIF.h>
#import <SDWebImage/SDWebImage.h>


@implementation UIImageView (JW)


- (void)setImageWithUrl:(NSString *)imageUrl
{
    [self setImageWithUrl:imageUrl PlaceHolder:[UIImage imageNamed:@"defaultImage"]];
}


- (void)setVideoImageWithUrl:(NSString *)videoUrl{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // Do the work in background
        UIImage *image = [FlyClientTools thumbnailImageForVideo:[NSURL URLWithString:[videoUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] atTime:0];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.image = image;
        });
    });
}

- (void)setImageWithUrl:(NSString *)imageUrl PlaceHolder:(UIImage *)placeHolderImage
{
    NSURL *url = [NSURL URLWithString:[imageUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    if(url){
        [self sd_setImageWithURL:url placeholderImage:placeHolderImage options:0 progress:0 completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            
        }];
        if([imageUrl hasSuffix:@".gif"]){
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                NSData *data = [[SDImageCache sharedImageCache] diskImageDataForKey:imageUrl];
                if(!data){
                    data = [NSData dataWithContentsOfURL:url];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    if(data){
                        [[SDImageCache sharedImageCache] storeImage:self.image imageData:data forKey:imageUrl toDisk:YES completion:nil];
                    }
//                    self.image = [UIImage sd_animatedGIFWithData:data];
                    [UIImage sd_imageWithGIFData:data];
                });
            });
        }
       
    }else{
        self.image = placeHolderImage;
    }
}


@end
